package com.gwz.cardserver.global;

import com.gwz.cardserver.dto.fight.FightRoom;
import com.gwz.cardserver.dto.fight.PlayerDto;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Data
@Component
public class FightCache {
    /**
     * 用户id 对应的房间id
     */
    private ConcurrentHashMap<String, Integer> uidRoomIdMap = new ConcurrentHashMap<>();
    /**
     * 房间id对应房间
     */
    private ConcurrentHashMap<Integer, FightRoom> idRoomDict = new ConcurrentHashMap<>();
    /**
     * 重用房间队列
     */
    private LinkedList<FightRoom> roomQueue = new LinkedList<>();
    /**
     * 当前房间id
     */
    private int currentId = -1;

    public FightRoom create(List<String> uids) {
        FightRoom room = null;
        if (roomQueue.size() > 0) {
            room = roomQueue.pop();
            room.init(uids);
        } else {
            room = new FightRoom(++currentId, uids);
        }

        for (String uid : uids) {
            uidRoomIdMap.put(uid, room.getId());
        }
        idRoomDict.put(room.getId(), room);
        return room;
    }

    public FightRoom getRoom(int id) {
        if (idRoomDict.containsKey(id) == false) {
            throw new IllegalArgumentException("不存在这个房间");
        }
        return idRoomDict.get(id);
    }

    /**
     * 根据玩家id获取房间
     *
     * @param userId
     * @return
     */
    public FightRoom getRoomByUserId(String userId) {
        if (uidRoomIdMap.containsKey(userId) == false) {
            throw new IllegalArgumentException("不存在这个玩家");
        }
        Integer roomId = uidRoomIdMap.get(userId);
        return getRoom(roomId);
    }

    /**
     * 当前用户是否在战斗房间
     * @param userId
     * @return
     */
    public boolean isFighting(String userId){
        return uidRoomIdMap.containsKey(userId);
    }

    /**
     * 摧毁房间
     *
     * @param room
     */
    public void destory(FightRoom room) {
        idRoomDict.remove(room.getId());
        for (PlayerDto player : room.getPlayers()) {
            uidRoomIdMap.remove(player.getUserId());
        }
        room.getPlayers().clear();
        room.getLeaveUids().clear();
        room.getTableCardList().clear();
        room.getLibraryModel().init();
        room.setMultiple(1);
        room.roundModel.init();
        roomQueue.push(room);
    }


}
